<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="单据号" prop="serialNo">
        <el-input
          v-model="queryParams.serialNo"
          placeholder="请输入单据号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="调度单号" prop="dispatchBillNo">
        <el-input
          v-model="queryParams.dispatchBillNo"
          placeholder="请输入调度单号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车牌号" prop="plateNo">
        <el-input
          v-model="queryParams.plateNo"
          placeholder="请输入车牌号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="配送状态" prop="billStatus">
        <el-select v-model="queryParams.billStatus" placeholder="请选择配送状态" clearable filterable size="small">
          <el-option
            v-for="dict in billStatusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="配送时间" prop="deliveryTime">
        <el-date-picker clearable size="small"
                        v-model="queryParams.deliveryTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择配送时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="到达时间" prop="arriveTime">
        <el-date-picker clearable size="small"
                        v-model="queryParams.arriveTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择到达时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="客户" prop="customerId">
        <el-select v-model="queryParams.customerId" placeholder="请选择客户" clearable filterable size="small">
          <el-option
            v-for="dict in customerIdOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['wms:deliveryBill:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['wms:deliveryBill:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['wms:deliveryBill:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['wms:deliveryBill:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="deliveryBillList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="编号" align="center" prop="id"/>
      <el-table-column label="单据号" align="center" prop="serialNo" show-overflow-tooltip/>
      <el-table-column label="调度单号" align="center" prop="dispatchBillNo" show-overflow-tooltip/>
      <el-table-column label="车牌号" align="center" prop="plateNo" show-overflow-tooltip/>
      <el-table-column label="司机" align="center" prop="driver" show-overflow-tooltip/>
      <el-table-column label="司机联系电话" align="center" prop="contactTel"/>
      <el-table-column label="配送状态" align="center" prop="billStatus" :formatter="billStatusFormat"
                       show-overflow-tooltip
      />
      <el-table-column label="配送时间" align="center" prop="deliveryTime" width="180" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.deliveryTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="到达时间" align="center" prop="arriveTime" width="180" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.arriveTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="客户" align="center" prop="customerId" :formatter="customerIdFormat"
                       show-overflow-tooltip
      />
      <el-table-column label="客户联系人" align="center" prop="customerContact" show-overflow-tooltip/>
      <el-table-column label="客户联系电话" align="center" prop="customerContactTel" show-overflow-tooltip/>
      <el-table-column label="配送地址" align="center" prop="deliveryAddress" show-overflow-tooltip/>
      <el-table-column label="发货地址" align="center" prop="shipAddress" show-overflow-tooltip/>
      <el-table-column label="操作" width="250" align="center" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['wms:deliveryBill:edit']"
          >修改
          </el-button>
          <el-button size="mini"
                     type="text"
                     icon="el-icon-edit"
                     @click="peiSong(scope.row)"
          >配送
          </el-button>
          <el-button size="mini"
                     type="text"
                     icon="el-icon-edit"
                     @click="shouHuo(scope.row)"
          >收货
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['wms:deliveryBill:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改配送管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px" :inline="true">
        <el-form-item label="单据号" prop="serialNo">
          <el-input v-model="form.serialNo" placeholder="请输入单据号"/>
        </el-form-item>
        <el-form-item label="调度单号" prop="dispatchBillNo">
          <el-input disabled v-model="form.dispatchBillNo" placeholder="请输入调度单号">
            <el-button slot="append" @click="handleSelectDispatchBill">选择</el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="车牌号" prop="plateNo">
          <el-input v-model="form.plateNo" placeholder="请输入车牌号"/>
        </el-form-item>
        <el-form-item label="司机" prop="driver">
          <el-input v-model="form.driver" placeholder="请输入司机"/>
        </el-form-item>
        <el-form-item label="司机联系电话" prop="contactTel">
          <el-input v-model="form.contactTel" placeholder="请输入司机联系电话"/>
        </el-form-item>
        <el-form-item label="配送状态" prop="billStatus">
          <el-select v-model="form.billStatus" placeholder="请选择配送状态" clearable filterable>
            <el-option
              v-for="dict in billStatusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="配送时间" prop="deliveryTime">
          <el-date-picker clearable size="small"
                          v-model="form.deliveryTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择配送时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="到达时间" prop="arriveTime">
          <el-date-picker clearable size="small"
                          v-model="form.arriveTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择到达时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="客户" prop="customerId">
          <el-select v-model="form.customerId" placeholder="请选择客户" clearable filterable>
            <el-option
              v-for="dict in customerIdOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户联系人" prop="customerContact">
          <el-input v-model="form.customerContact" placeholder="请输入客户联系人"/>
        </el-form-item>
        <el-form-item label="客户联系电话" prop="customerContactTel">
          <el-input v-model="form.customerContactTel" placeholder="请输入客户联系电话"/>
        </el-form-item>
        <el-form-item label="配送地址" prop="deliveryAddress">
          <el-input v-model="form.deliveryAddress" placeholder="请输入配送地址"/>
        </el-form-item>
        <el-form-item label="发货地址" prop="shipAddress">
          <el-input v-model="form.shipAddress" placeholder="请输入发货地址"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注"/>
        </el-form-item>
        <el-divider content-position="center">配送单明细信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddWmsDeliveryBillDetail">添加
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteWmsDeliveryBillDetail">删除
            </el-button>
          </el-col>
        </el-row>
        <el-table :data="wmsDeliveryBillDetailList" :row-class-name="rowWmsDeliveryBillDetailIndex"
                  @selection-change="handleWmsDeliveryBillDetailSelectionChange" ref="wmsDeliveryBillDetail"
        >
          <el-table-column type="selection" width="50" align="center"/>
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="物料" prop="materialId" width="150">
            <template slot-scope="scope">
              <el-form-item :prop="'wmsDeliveryBillDetailList.'+scope.$index+'.materialId'" :rules="rules.materialId">
                <el-select v-model="scope.row.materialId" placeholder="请选择物料">
                  <el-option
                    v-for="dict in materialIdOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="parseInt(dict.dictValue)"
                  ></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="生产批号" prop="batchNo" width="150">
            <template slot-scope="scope">
              <el-form-item :prop="'wmsDeliveryBillDetailList.'+scope.$index+'.batchNo'" :rules="rules.batchNo">
                <el-input v-model="scope.row.batchNo" placeholder="请输入生产批号"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="仓库" prop="warehouseId" width="150">
            <template slot-scope="scope">
              <el-form-item :prop="'wmsDeliveryBillDetailList.'+scope.$index+'.warehouseId'" :rules="rules.warehouseId">
                <el-select v-model="scope.row.warehouseId" placeholder="请选择仓库">
                  <el-option
                    v-for="dict in warehouseIdOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="parseInt(dict.dictValue)"
                  ></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="库区" prop="whRegionId" width="150">
            <template slot-scope="scope">
              <el-form-item :prop="'wmsDeliveryBillDetailList.'+scope.$index+'.whRegionId'" :rules="rules.whRegionId">
                <el-select v-model="scope.row.whRegionId" placeholder="请选择库区">
                  <el-option
                    v-for="dict in whRegionIdOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="parseInt(dict.dictValue)"
                  ></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="库位" prop="whLocationId" width="150">
            <template slot-scope="scope">
              <el-form-item :prop="'wmsDeliveryBillDetailList.'+scope.$index+'.whLocationId'"
                            :rules="rules.whLocationId"
              >
                <el-select v-model="scope.row.whLocationId" placeholder="请选择库位">
                  <el-option
                    v-for="dict in whLocationIdOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="parseInt(dict.dictValue)"
                  ></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="发货数量" prop="deliveryQuantity" width="150">
            <template slot-scope="scope">
              <el-form-item :prop="'wmsDeliveryBillDetailList.'+scope.$index+'.deliveryQuantity'"
                            :rules="rules.deliveryQuantity"
              >
                <el-input v-model="scope.row.deliveryQuantity" placeholder="请输入发货数量"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="价格" prop="price" width="150">
            <template slot-scope="scope">
              <el-form-item :prop="'wmsDeliveryBillDetailList.'+scope.$index+'.price'" :rules="rules.price">
                <el-input v-model="scope.row.price" placeholder="请输入价格"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="detailRemark" width="150">
            <template slot-scope="scope">
              <el-form-item :prop="'wmsDeliveryBillDetailList.'+scope.$index+'.detailRemark'"
                            :rules="rules.detailRemark"
              >
                <el-input v-model="scope.row.detailRemark" placeholder="请输入备注"/>
              </el-form-item>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="选择调度单" :visible.sync="openSelectDispatchBill" width="1000px" append-to-body>
      <!-- <DispatchBill @onClose="handleDispatchBillClose" @onSelect="handleDispatchBillSelect"></DispatchBill>-->
      <MaterialSelectTest/>
    </el-dialog>
  </div>
</template>

<script>
import {
  addDeliveryBill,
  delDeliveryBill,
  exportDeliveryBill,
  getDeliveryBill,
  listDeliveryBill,
  updateDeliveryBill
} from '@/api/wms/deliveryBill'
import { parseTime } from '../../../utils/neu'
import DispatchBill from '@/views/wms/dispatchBill/index.vue'
import MaterialSelectTest from '@/components/tempComponent/MaterialSelect.vue'
import fa from 'element-ui/src/locale/lang/fa'

export default {
  name: 'DeliveryBill',
  components: { MaterialSelectTest, DispatchBill },
  data() {
    return {
      openSelectDispatchBill: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedWmsDeliveryBillDetail: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 配送管理表格数据
      deliveryBillList: [],
      // 配送单明细表格数据
      wmsDeliveryBillDetailList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 配送状态字典
      billStatusOptions: [],
      // 客户字典
      customerIdOptions: [],
      // 物料字典
      materialIdOptions: [],
      // 仓库字典
      warehouseIdOptions: [],
      // 库区字典
      whRegionIdOptions: [],
      // 库位字典
      whLocationIdOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        serialNo: null,
        dispatchBillNo: null,
        plateNo: null,
        billStatus: null,
        deliveryTime: null,
        arriveTime: null,
        customerId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        plateNo: [
          { required: true, message: '车牌号不能为空', trigger: 'blur' }
        ],
        deliveryTime: [
          { required: true, message: '配送时间不能为空', trigger: 'blur' }
        ],
        deliveryAddress: [
          { required: true, message: '配送地址不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getDicts('delivery_status').then(response => {
      this.billStatusOptions = response.data
    })
    this.getQueryData('query_customer').then(res => {
      this.customerIdOptions = res.data
    })
    this.getQueryData('query_material').then(res => {
      this.materialIdOptions = res.data
    })
    this.getQueryData('query_warehouse').then(res => {
      this.warehouseIdOptions = res.data
    })
    this.getQueryData('query_warehouse_region').then(res => {
      this.whRegionIdOptions = res.data
    })
    this.getQueryData('query_warehouse_location').then(res => {
      this.whLocationIdOptions = res.data
    })
  },
  watch: {
    'wmsDeliveryBillDetailList': {
      handler(newVal, oldVal) {
        this.form.wmsDeliveryBillDetailList = newVal
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    handleDispatchBillSelect(row) {
      this.$set(this.form, 'dispatchBillNo', row.serialNo)
      this.openSelectDispatchBill = false
    },
    handleDispatchBillClose() {
      this.openSelectDispatchBill = false
    },
    handleSelectDispatchBill() {
      this.openSelectDispatchBill = true
    },
    peiSong(row) {
      const id = row.id
      updateDeliveryBill({ id: id, billStatus: '2' }).then(response => {
        this.msgSuccess('开始配送')
        this.getList()
      })
    },
    shouHuo(row) {
      const id = row.id
      updateDeliveryBill({ id: id, billStatus: '1' }).then(response => {
        this.msgSuccess('收货成功')
        this.getList()
      })
    },
    parseTime,
    /** 查询配送管理列表 */
    getList() {
      this.loading = true
      listDeliveryBill(this.queryParams).then(response => {
        this.deliveryBillList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 配送状态字典翻译
    billStatusFormat(row, column) {
      return this.selectDictLabel(this.billStatusOptions, row.billStatus)
    },
    // 客户字典翻译
    customerIdFormat(row, column) {
      return this.selectDictLabel(this.customerIdOptions, row.customerId)
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        serialNo: null,
        dispatchBillId: null,
        dispatchBillNo: null,
        plateNo: null,
        driver: null,
        contactTel: null,
        billStatus: null,
        deliveryTime: null,
        arriveTime: null,
        customerId: null,
        customerContact: null,
        customerContactTel: null,
        deliveryAddress: null,
        shipAddress: null,
        remark: null,
        wmsDeliveryBillDetailList: []
      }
      this.wmsDeliveryBillDetailList = []
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加配送管理'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getDeliveryBill(id).then(response => {
        this.form = response.data
        this.wmsDeliveryBillDetailList = response.data.wmsDeliveryBillDetailList
        this.open = true
        this.title = '修改配送管理'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {

          if (this.form.id != null) {
            updateDeliveryBill(this.form).then(response => {
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addDeliveryBill(this.form).then(response => {
              this.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$confirm('是否确认删除配送管理编号为"' + ids + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delDeliveryBill(ids)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      })
    },
    /** 配送单明细序号 */
    rowWmsDeliveryBillDetailIndex({ row, rowIndex }) {
      row.index = rowIndex + 1
    },
    /** 配送单明细添加按钮操作 */
    handleAddWmsDeliveryBillDetail() {
      let obj = {}
      obj.materialId = ''
      obj.batchNo = ''
      obj.warehouseId = ''
      obj.whRegionId = ''
      obj.whLocationId = ''
      obj.deliveryQuantity = ''
      obj.price = ''
      obj.detailRemark = ''
      this.wmsDeliveryBillDetailList.push(obj)
    },
    /** 配送单明细删除按钮操作 */
    handleDeleteWmsDeliveryBillDetail() {
      if (this.checkedWmsDeliveryBillDetail.length == 0) {
        this.$alert('请先选择要删除的配送单明细数据', '提示', { confirmButtonText: '确定' })
      } else {
        this.wmsDeliveryBillDetailList.splice(this.checkedWmsDeliveryBillDetail[0].index - 1, 1)
      }
    },
    /** 单选框选中数据 */
    handleWmsDeliveryBillDetailSelectionChange(selection) {
      if (selection.length > 1) {
        this.$refs.wmsDeliveryBillDetail.clearSelection()
        this.$refs.wmsDeliveryBillDetail.toggleRowSelection(selection.pop())
      } else {
        this.checkedWmsDeliveryBillDetail = selection
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm('是否确认导出所有配送管理数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return exportDeliveryBill(queryParams)
      }).then(response => {
        this.download(response.msg)
      })
    }
  }
}
</script>
